// pages/admin/create/create.js
const cloud = wx.cloud;
const db = cloud.database()
var MD5 = require('../../../utils/md5.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        _w: 80,
        fileList: [],
        steps: [
            {
                text: "选择并上传"
            },
            {
                text: "存入数据库"
            },
            {
                text: "上传完成"
            }
        ],
        step_active: 0,
        s_width: 0,
    },

    imgloadsize: function (e) {
        console.log('imgloadsize', e)
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.getSystemInfo({
          success: (result) => {
              this.setData({
                  _w: (result.screenWidth - 54)/3,
                  s_width: (result.screenWidth - 20) / 3 - 10
              })
          },
        })
    },
    afterRead: function (e) {
        const { file } = e.detail;
        let { fileList } = this.data;
        if (fileList.length > 0) {
            this.setData({
                fileList: fileList.concat(file)
            })
        } else {
            this.setData({
                fileList: file
            })
        }
    },
    // 删除图片
    delete: function (e) {
        let { fileList } = this.data
        let { index } = e.detail
        let that = this
        wx.showModal({
            title: "确定删除这张图片吗",
            success: function (res) {
                if (res.confirm) {
                    fileList.splice(index,1)
                    that.setData({
                        fileList: fileList
                    })
                }
            }
        })
    },
    // 上传图片
    uploadToCloud: function () {
        let {
            fileList
        } = this.data;
        if (!fileList.length) {
            wx.showToast({
                title: '请选择图片',
                icon: 'none'
            })
        } else {
            wx.showLoading({
              title: '上传中',
            })
            const uploadTasks = fileList.map((file, index) => this.uploadFilePromise(file));
            Promise.all(uploadTasks)
                .then(data => {
                    // wx.showToast({
                    //     title: '上传成功',
                    //     icon: 'none'
                    // });
                    console.log(data)
                    // data.map((item, index) => {
                    //     console.log(index, item)
                    //     wx.getImageInfo({
                    //       src: item.fileID,
                    //     }).then((ret)=>{
                    //         console.log(ret)
                    //     })
                    //     // db.collection("Images").add();
                    // });

                    
                    // wx.cloud.callFunction({
                    //     name: "album"
                    // })

                    const newFileList = data.map(item => ({
                        url: item.fileID
                    }));

                    setTimeout(()=>{
                        wx.hideLoading({
                          success: (res) => {
                              wx.showToast({
                                title: '上传完成',
                                icon: 'none'
                              })
                          },
                        })
                    },1000)
                    
                    this.setData({
                        step_active: 1,
                        cloudPath: data,
                        fileList: newFileList
                    });
                })
                .catch(e => {
                    wx.showToast({
                        title: '上传失败',
                        icon: 'none'
                    })
                    console.log(e);
                });
        }

    },

    // 写入数据库
    saveCollection: function () {
        console.log("写入数据库");
        let { cloudPath } = this.data
        const createCollectionTask = cloudPath.map((img, index) => this.createCollection(img.fileID))
        Promise.all(createCollectionTask).then((res)=>{
            console.log(res)
            this.setData({
                step_active: 2
            })
        })
    },

    createCollection: function (fileID) {
        return  db.collection("Images").add({
            data: {
                fileID: fileID
            }
        });
    },

    uploadFilePromise: function (chooseResult) {
        // console.log("uploadFilePromise: ", chooseResult)
        // return cloud.uploadFile({});
        // 获取图片路径
        let img = chooseResult.url
        // 获取图片名称
        let time = new Date();
        let savePath = "images/" + time.getFullYear() + "-" + time.getMonth()+1 + "/";
        let fileName = img.substr(11);
        return cloud.uploadFile({
            cloudPath: savePath + fileName,
            filePath: chooseResult.url
        })
        // 获取图片信息
        // wx.getImageInfo({
        //   src: img,
        // }).then((ret)=>{
        //     // console.log("获取图片信息", ret)
        //     let width = ret.width, height = ret.height, type = ret.type;
        //     cloud.uploadFile({
        //         cloudPath: savePath + fileName,
        //         filePath: chooseResult.url
        //     }).then((ret2)=>{
        //         // console.log("上传图片", ret2)
        //         // 写入数据库
        //         db.collection("Images").add({
        //             data: {
        //                 src: ret2.fileID,
        //                 width: width,
        //                 height: height,
        //                 type: type,
        //                 create_time: new Date()
        //             },
        //             success: function (res) {
        //                 console.log("db.", res)
        //                 return res._id
        //             }
        //         })
        //     })
        // })
    },

    beforeRead: function (e) {
        const {
            file,
            callback
        } = e.detail;
        callback(file.type === 'image');
    },

    default: function () {
        this.setData({
            step_active: 0,
            fileList: [],
            cloudPath: []
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})